package electionView;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;

public class ToneGen {

	public void happySound(){
		generateTone(587,150,20,true);//d5
		generateTone(392,150,20,true);//g4
		generateTone(392,150,20,true);//g4
	}
	/**
	 * credit for this method goes to the java/ sun website
	 * @param hz the frequency of the note 
	 * @param msecs the length
	 * @param volume the volume
	 * @param addHarmonic harmonize note
	 * @throws LineUnavailableException 
	 */
	public static void generateTone(int hz,int msecs, int volume, boolean addHarmonic)
	{
		float frequency = 44100;
		byte[] buf;
		AudioFormat af;
		if (addHarmonic)
		{
			buf = new byte[2];
			af = new AudioFormat(frequency,8,2,true,false);
		}
		else
		{
			buf = new byte[1];
			af = new AudioFormat(frequency,8,1,true,false);
		}
		SourceDataLine sdl = null;
		try
		{
			sdl = AudioSystem.getSourceDataLine(af);
//			sdl = AudioSystem.getSourceDataLine(af);
			sdl.open(af);
		}
		catch(LineUnavailableException e)
		{
			e.printStackTrace();
			return;
		}
		sdl.start();
		for(int i=0; i<msecs*frequency/1000; i++)
		{
			double angle = i/(frequency/hz)*2.0*Math.PI;
			buf[0]=(byte)(Math.sin(angle)*volume);

			if(addHarmonic)
			{
				double angle2 = (i)/(frequency/hz)*2.0*Math.PI;
				buf[1]=(byte)(Math.sin(2*angle2)*volume*0.6);
				sdl.write(buf,0,2);
			}
			else
			{
				sdl.write(buf,0,1);
			}
		}
		sdl.drain();
		sdl.stop();
		sdl.close();
	}
}
